/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.iecg.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.iecg.filter.RequestHolder;
import com.iecg.service.IecgMobileService;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.constant.enums.LoginTypeEnum;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author lengleng
 * @date 2018/11/14
 * <p>
 * 手机登录相关业务实现
 */
@Slf4j
@Service
@AllArgsConstructor
public class IecgMobileServiceImpl implements IecgMobileService {
	private final RedisTemplate redisTemplate;


	/**
	 * 发送手机验证码
	 * TODO: 调用短信网关发送验证码,测试返回前端
	 *
	 * @param mobile mobile
	 * @return code
	 */
	@Override
	public R<Boolean> sendSmsCode(String mobile) {

		Object codeObj = redisTemplate.opsForValue().get(CommonConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + "@" + mobile);

		if (codeObj != null) {
			log.info("手机号验证码未过期:{}，{}", mobile, codeObj);
			return R.ok(Boolean.FALSE, "验证码发送过频繁");
		}

		String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE));
		if(code.startsWith("0")){
			code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE));
		}
		invokeAliyunSdkCode(mobile, code);
		log.debug("手机号生成验证码成功:{},{}", mobile, code);
		redisTemplate.opsForValue().set(
			CommonConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + "@" + mobile
			, code, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
		return R.ok(Boolean.TRUE, code);
	}

	@Override
	public boolean checkCode(String phone, String code) {
		String redisCode = (String) redisTemplate.opsForValue().get(CommonConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + "@" + phone);
		return code.equals(redisCode);
	}


	/**
	 * 调用阿里云短信sdk
	 * @param mobile
	 * @param code
	 */
	public void  invokeAliyunSdkCode(String mobile, String code){
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FhJr6VmHvvW3QYYtYPX", "1fJhXxbk1JzODYO7v4zYEZWmd2oZvJ");
		IAcsClient client = new DefaultAcsClient(profile);

		CommonRequest request = new CommonRequest();
		request.setMethod(MethodType.POST);
		request.setDomain("dysmsapi.aliyuncs.com");
		request.setVersion("2017-05-25");
		request.setAction("SendSms");
		request.putQueryParameter("RegionId", "cn-hangzhou");
		request.putQueryParameter("PhoneNumbers", mobile);
		request.putQueryParameter("SignName", "中科华师");  //签名，目前只有一个“中科华师”
		//SMS_177544016  注册验证码    ：您的校验码：${code}，您正在注册成为会员，感谢您的支持！
		//SMS_177554099  忘记密码验证码 ：您的动态码为：${code}，您正在进行密码重置操作，如非本人操作，请忽略本短信！
		//SMS_177549028  添加联系人验证码：您的校验码：${code}，正在进行添加紧急联系人操作。
		//SMS_182678337  您的动态码为：${code},您正在进行亲友绑定操作，如非本人操作，请忽略本短信！
		String smsTemplate;
		String templateType = RequestHolder.getParam();
		switch (templateType){
			case "p":
				smsTemplate = "SMS_177554099";
				break;
			case "e":
				smsTemplate = "SMS_177549028";
				break;
			case  "b":
				smsTemplate = "SMS_182677387";
				break;
			case "q":
				smsTemplate = "SMS_182678337";
				break;
			default:
				smsTemplate = "SMS_177544016";
		}
		request.putQueryParameter("TemplateCode", smsTemplate);
		request.putQueryParameter("TemplateParam", "{\"code\":" + code + "}");


		try {
			CommonResponse response = client.getCommonResponse(request);
			System.out.println(response.getData());
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
	}
}
